package model

import (
	"vueBasic/app/admin/filter"
	"vueBasic/extend/conv"
	"vueBasic/global"
)

var DocM = new(docModel)

type docModel struct {
	Id         uint   `form:"id" json:"id"`
	Title      string `form:"title" json:"title"` //标题
	Type       int    `form:"type" json:"type"`
	BookId     int    `form:"book_id" json:"book_id"`
	AdminId    int    `form:"admin_id" json:"admin_id"`
	Link       string `form:"link" json:"link"`
	Pid        int    `form:"pid" json:"pid"`
	Status     int    `form:"status" json:"status"`
	Sort       int    `form:"sort" json:"sort"`
	Content    string `form:"content" json:"content"`
	AddTime    int64  `form:"add_time" json:"add_time"`
	UpdateTime int64  `form:"update_time" json:"update_time"`
	DeleteTime int64  `form:"delete_time" json:"delete_time"`
}

func (*docModel) TableName() string {
	return global.CONF.Database.Db.Prefix + "doc"
}

func (*docModel) GetList(req *filter.DocReq) ([]docModel, int64, error) {
	var (
		docList []docModel
		count   int64
	)
	query := global.DB.Model(&docModel{})
	if !conv.IsEmpty(req.BookId) {
		query = query.Where("book_id=?", req.BookId)
	}

	if err := query.Order("sort ASC").Find(&docList).Error; err != nil {
		return nil, 0, err
	}
	//获取总条数
	query.Count(&count)
	return docList, count, nil
}

func (*docModel) Add(req *filter.DocAddReq) (uint, error) {
	entity := docModel{}
	entity.Title = req.Title
	entity.Sort = req.Sort
	entity.Status = req.Status
	entity.Pid = req.Pid
	entity.BookId = req.BookId
	entity.Type = req.Type
	entity.AddTime = req.AddTime
	entity.UpdateTime = req.UpdateTime
	if err := global.DB.Create(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

func (*docModel) GetDocById(id int) (*docModel, error) {
	entity := docModel{}
	if err := global.DB.Where("id=?", id).Limit(1).First(&entity).Error; err != nil {
		return nil, err
	}
	return &entity, nil
}

func (*docModel) Update(req *filter.DocUpdateReq) (uint, error) {
	entity := docModel{Id: req.Id}
	global.DB.First(&entity)
	entity.Title = req.Title
	entity.Sort = req.Sort
	entity.Status = req.Status
	entity.Pid = req.Pid
	entity.BookId = req.BookId
	entity.Type = req.Type
	entity.UpdateTime = req.UpdateTime
	if err := global.DB.Save(&entity).Error; err != nil {
		return 0, err
	}
	return entity.Id, nil
}

func (*docModel) UpdateExt(req map[string]interface{}) error {
	query := global.DB.Model(&docModel{})
	if err := query.Where("id=?", req["id"]).Updates(req).Error; err != nil {
		return err
	}
	return nil
}

func (*docModel) Delete(ids []string) (uint, error) {
	query := global.DB.Where("id IN ?", ids)
	err := query.Delete(&docModel{}).Error
	if err != nil {
		return 0, err
	}
	return 1, nil
}
